package com.zk.util;

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * word转PDF
 *
 * <p>只支持 DOC、DOCX 格式
 */
public class Word2PdfUtil {

    private Word2PdfUtil() {
    }

    /**
     * doc格式文件转pdf
     *
     * @param inputStream 文件流
     * @param targetPath  全路径，例如：C:\Users\PC\Desktop\doc.pdf
     */
    public static void doc2Pdf(InputStream inputStream, String targetPath) {
        try (FileOutputStream os = new FileOutputStream(targetPath)) {
            // Address是将要被转化的word文档
            Document doc = new Document(inputStream);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(os, SaveFormat.PDF);
        } catch (Exception ex) {
            String content;
            StringBuilder sb;
            try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "GBK"))) {
                sb = new StringBuilder();
                String line;
                // 阻塞
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    sb.append("\n");
                }
                content = sb.substring(sb.indexOf("<html>"), sb.indexOf("</html>"));
                content =
                        content.replace(
                                "<html>",
                                "<html> <head>\n"
                                        + "  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"
                                        + "  <meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />\n"
                                        + "  <title></title>\n"
                                        + " </head>");
                String html = targetPath.replace("pdf", "html");
                try (FileOutputStream htmlOut = new FileOutputStream(html)) {
                    htmlOut.write(content.getBytes(StandardCharsets.UTF_8));
                    htmlOut.flush();
                }
                try (FileOutputStream fileOutputStream = new FileOutputStream(targetPath);
                     InputStream is = new FileInputStream(html)) {
                    // Address是将要被转化的word文档
                    Document doc = new Document(is);
                    // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
                    doc.save(fileOutputStream, SaveFormat.PDF);
                }
            } catch (Exception e) {
                throw new RuntimeException("doc2pdf 出错", e);
            }
        }
    }
}
